import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    Alert,
    FlatList,
    TextInput,
    Linking,
    DeviceEventEmitter,
    ScrollView, PermissionsAndroid
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import Loading from "../../utils/Loading";
import { getImgUrl } from '../../utils/ComFunction'
import ActionSheet from 'react-native-actionsheet'
import Upload from '../../components/upload/Upload'
import ImageCropPicker from 'react-native-image-crop-picker';
import RegionPickerView from '../../components/Tool/RegionPickerView';

import PermissionDialog from "../../components/dialog/PermissionDialog";
const isIos = Platform.OS == 'ios';

let navigation

let imgType = ''

export default class StoreEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {},
            remarkMaxLength: 500,
            showAreaPicker: false,
            dialogVisible: false,
        }
    }

    componentDidMount() {

        this.selectMapResult = DeviceEventEmitter.addListener('selectMapResult', result => {
            console.log('selectMapResult', result)
            if (result.lat) {
                let data = this.state.data
                data.lat = result.lat
                data.lon = result.lon
                if (!data.address) {
                    data.address = result.address
                }
                this.setState({
                    data: data
                })
            }

        });

        this.getStoreInfo()
    }

    componentWillUnmount() {
        if (this.selectMapResult) {
            this.selectMapResult.remove();
        }

    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'门店设置'} RightButton={() => this.renderRightButton()}></Header>

                <View style={{ flex: 1 }}>
                    <ScrollView>
                        <View style={styles.storeInfoBox}>
                            <TouchableOpacity
                                style={{ width: '100%', height: '100%' }}
                                activeOpacity={0.8}
                                onPress={() => {
                                    this.tapStoreImg()
                                }}
                            >
                                {
                                    this.state.data.storePic ?
                                        <Image style={styles.storeImg} source={{ uri: getImgUrl(this.state.data.storePic) }} />
                                        :
                                        <Image style={styles.storeImg} source={require('source/image/company_header_icon.png')} />
                                }
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={styles.storeBottomBox}
                                activeOpacity={0.8}
                                onPress={() => {
                                    this.tapLogoImg()
                                }}
                            >
                                <Text style={styles.storeLogoText}>公司LOGO</Text>
                                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    {
                                        this.state.data.merchantLogoPic ?
                                            <Image style={styles.logoImg} source={{ uri: getImgUrl(this.state.data.merchantLogoPic) }} />
                                            :
                                            <Image style={styles.logoImg} source={require('source/image/comm/sc_default.png')} />
                                    }
                                    <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={[styles.sectionBox, { marginTop: 10 }]}>
                            <View style={styles.storeItemBox}>
                                <View style={styles.leftBox}>
                                    <Text style={styles.storeTitleText}>公司全称</Text>
                                    <Text style={styles.necessaryText}>*</Text>
                                </View>
                                <TextInput
                                    editable={false}
                                    clearButtonMode='while-editing'
                                    style={styles.textInput}
                                    placeholder='请输入公司全称'
                                    returnKeyType='done'
                                    value={this.state.data.merchantName}
                                />
                            </View>
                            <View style={styles.storeItemBox1}>
                                <View style={styles.leftBox}>
                                    <Text style={styles.storeTitleText}>公司简称</Text>
                                    <Text style={styles.necessaryText}>*</Text>
                                </View>
                                <TextInput
                                    clearButtonMode='while-editing'
                                    style={styles.textInput}
                                    placeholder='请输入公司简称'
                                    returnKeyType='done'
                                    value={this.state.data.merchantAbbreviation}
                                    onChangeText={this.changeText.bind(this, 'merchantAbbreviation')}
                                />
                            </View>
                        </View>
                        <View style={[styles.sectionBox, { marginTop: 10 }]}>
                            <View style={styles.storeItemBox}>
                                <View style={styles.leftBox}>
                                    <Text style={styles.storeTitleText}>联系人</Text>
                                    <Text style={styles.necessaryText}>*</Text>
                                </View>
                                <TextInput
                                    clearButtonMode='while-editing'
                                    style={styles.textInput}
                                    placeholder='请输入联系人'
                                    returnKeyType='done'
                                    value={this.state.data.owner}
                                    onChangeText={this.changeText.bind(this, 'owner')}
                                />
                            </View>
                            <View style={styles.storeItemBox}>
                                <View style={styles.leftBox}>
                                    <Text style={styles.storeTitleText}>联系电话</Text>
                                    <Text style={styles.necessaryText}>*</Text>
                                </View>
                                <TextInput
                                    clearButtonMode='while-editing'
                                    style={styles.textInput}
                                    placeholder='请输入联系电话'
                                    returnKeyType='done'
                                    maxLength={11}
                                    keyboardType='number-pad'
                                    value={this.state.data.phone}
                                    onChangeText={this.changeText.bind(this, 'phone')}
                                />
                            </View>
                            <TouchableOpacity
                                style={styles.storeItemBox}
                                onPress={() => {
                                    this.selectArea()
                                }}
                            >
                                <View style={styles.leftBox}>
                                    <Text style={styles.storeTitleText}>地区</Text>
                                    <Text style={styles.necessaryText}>*</Text>
                                </View>
                                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', flex: 1, marginLeft: 25 }}>
                                    <Text style={styles.storeTitleText}>{this.state.data.districtName ? this.state.data.provinceName + this.state.data.cityName + this.state.data.districtName : ''}</Text>
                                    <Image style={{ width: 15, height: 15 }} source={require('source/image/comm/icon_tree_arrow.png')} />
                                </View>
                            </TouchableOpacity>
                            <View style={styles.storeItemBox}>
                                <Text style={[styles.storeTitleText, { width: 68 }]}>详细地址</Text>
                                <TextInput
                                    clearButtonMode='while-editing'
                                    style={styles.textInput}
                                    placeholder='请输入详细地址'
                                    returnKeyType='done'
                                    value={this.state.data.address}
                                    onChangeText={this.changeText.bind(this, 'address')}
                                />
                            </View>
                            <TouchableOpacity
                                style={[styles.storeItemBox1, { justifyContent: 'flex-start' }]}
                                onPress={() => {
                                    this.location()
                                }}
                            >
                                <View style={styles.leftBox}>
                                    <Text style={styles.storeTitleText}>设置定位</Text>
                                    <Text style={styles.necessaryText}>*</Text>
                                </View>
                                <Image style={styles.locationImg} source={this.state.data.lat && this.state.data.lon ? require('source/image/in_location.png') : require('source/image/un_location.png')} />
                            </TouchableOpacity>
                        </View>
                        <View style={[styles.sectionBox, { marginTop: 10, minHeight: 100, paddingBottom: 12 }]}>
                            <Text style={[styles.storeTitleText, { marginTop: 14 }]}>公司介绍</Text>
                            <View style={styles.remarkBg}>
                                <TextInput
                                    clearButtonMode='while-editing'
                                    maxLength={this.state.remarkMaxLength}
                                    style={styles.remarkTextInput}
                                    placeholder='请输入公司介绍'
                                    multiline={true}
                                    value={this.state.data.merchantProfile}
                                    lineHeight={20}
                                    onChangeText={this.changeText.bind(this, 'merchantProfile')}
                                />
                                <Text style={styles.remarkCountText}>{(this.state.data && this.state.data.merchantProfile ? this.state.data.merchantProfile.length : '0') + '/' + this.state.remarkMaxLength}</Text>
                            </View>

                        </View>

                        <View
                            style={[styles.deleteBg, { height: Constant.bottomHeight + 50 }]}
                        >
                            <TouchableOpacity
                                style={styles.deleteBox}
                                onPress={() => {
                                    this.save()
                                }}
                            >
                                <Text style={styles.deleteText}>保存</Text>
                            </TouchableOpacity>
                        </View>
                    </ScrollView>
                </View>

                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'请选择照片来源 ?'}
                    options={['相册', '拍照', '取消']}
                    cancelButtonIndex={2}
                    onPress={(index) => { this.selectPhoto(index) }}
                />

                <RegionPickerView
                    show={this.state.showAreaPicker}
                    hide={() => {
                        this.setState({
                            showAreaPicker: false
                        })
                    }}
                    selectArea={(item) => {
                        this.setState({
                            showAreaPicker: false
                        })

                        let data = this.state.data
                        data.province = item.provinceId,
                            data.provinceName = item.provinceName
                        data.city = item.cityId,
                            data.cityName = item.cityName
                        data.district = item.areaId,
                            data.districtName = item.areaName
                    }}
                />

                <PermissionDialog
                    visible={this.state.dialogVisible}
                    onClose={() => this.setDialogVisible(false)}
                    title={'申请相机拍照权限和文件读写存储权限'}
                    content={'申请相机拍照权限，用于完成个人头像拍照;申请文件读写权限，用于完成拍照后的图片裁剪保存，完成头像上传'}
                    permissions={[
                        PermissionsAndroid.PERMISSIONS.CAMERA,
                        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
                    ]}
                />

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    renderRightButton() {
        return (
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={() => { this.deleteStore() }}>
                <View style={styles.rightBox}>
                    <Text style={styles.rightText}>注销门店</Text>
                </View>
            </TouchableOpacity>
        )
    }

    save() {
        if (this.state.data.merchantAbbreviation.length == 0) {
            ToastToUser('请填写公司简称')
            return
        }
        if (this.state.data.owner.length == 0) {
            ToastToUser('请填写联系人')
            return
        }
        if (this.state.data.phone.length == 0) {
            ToastToUser('请填写联系电话')
            return
        }
        if (this.state.data.districtName.length == 0) {
            ToastToUser('请选择地区')
            return
        }
        if (!this.state.data.lon || !this.state.data.lat || this.state.data.lon.length == 0 || this.state.data.lat.length == 0) {
            ToastToUser('请设置定位')
            return
        }

        if (this.Loading) {
            this.Loading.show('保存中...');
        }
        let param = {
            merchantId: Constant.userInfo.merchantId,
            ...this.state.data
        }
        HttpUtils.postRequest(HttpUrls.merchantUpdate, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    if (this.props.route.params && this.props.route.params.completion) {
                        this.props.route.params.completion()
                    }
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    getStoreInfo() {
        if (this.Loading) {
            this.Loading.show();
        }
        let param = {
            merchantId: Constant.userInfo.merchantId,
        }
        HttpUtils.getRequest(HttpUrls.getMerchantDetail, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    let data = result.data
                    this.setState({
                        data: data,
                    })
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    deleteStore() {
        Alert.alert('警告', '注销公司后，公司所有的车辆、员工、客户都会丢失，且无法恢复，您确定要注销吗?',
            [{ text: "取消" },
            {
                text: "继续注销", onPress: () => {
                    let param = {
                        merchantId: Constant.userInfo.merchantId,
                        userId: this.state.userId,
                        operator: Constant.userInfo.fullname
                    }
                    this.Loading.show('注销中...')
                    HttpUtils.getRequest(HttpUrls.cancellation, param)
                        .then((result) => {
                            this.Loading.hide()
                            if (result.code == 0) {
                                navigation.dispatch(StackActions.pop(2));
                                AndroidModule.logout()
                            } else {
                                ToastToUser(result.msg)
                            }
                        })
                        .catch((error) => {
                            this.Loading.hide()
                        });
                }
            }]
        )
    }

    //输入框内容输入
    changeText(type, val) {
        let data = this.state.data
        data[type] = val
        this.setState({
            data: data
        })
    }

    selectArea() {
        this.setState({
            showAreaPicker: true
        })
    }

    location() {
        let params = {
            lat: this.state.data.lat,
            lon: this.state.data.lon
        }
        console.log('location', params)
        AndroidModule.selectMap(params, (error, result) => {
            let data = this.state.data
            data.lat = result.lat
            data.lon = result.lon
            if (!data.address) {
                data.address = result.address
            }
            this.setState({
                data: data
            })
        })
    }

    tapStoreImg() {
        imgType = 'storeImg'
        this.ActionSheet.show()
    }

    tapLogoImg() {
        imgType = 'logoImg'
        this.ActionSheet.show()
    }

    //选择相册还是照相机
    selectPhoto(index) {
        if (index == 0) {
            //相册
            const option = { mediaType: "photo", cropping: false, compressImageQuality: .6, multiple: false, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
            ImageCropPicker.openPicker(option).then(images => {
                if (this.Loading) {
                    this.Loading.show('正在上传');
                }
                Upload.getAlipz(images.path, Upload.OSS_FACE, this.uploadafterfun);//获取阿里凭证。

            }, (error) => {
                // alert(error);
            });

        } else if (index == 1) {
            //照相机
            this.openCamera();
        }
    }


    openCamera() {
        if (isIos) {
            this.takePhoto()
        } else {
            PermissionsAndroid.check('android.permission.CAMERA').then(res => {
                if (!res) {

                    this.setDialogVisible(true)
                }
                else {
                    this.takePhoto()
                }
            })

        }
    }

    setDialogVisible(dialogVisible) {
        this.setState({
            dialogVisible: dialogVisible
        })
    }

    takePhoto() {
        const option = { mediaType: "photo", cropping: false, compressImageQuality: .8, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
        ImageCropPicker.openCamera(option).then(images => {
            if (this.Loading) {
                this.Loading.show()
            }
            Upload.getAlipz(images.path, Upload.OSS_FACE, this.uploadafterfun);//获取阿里凭证。

        }, (error) => {
            // alert(error);
        });
    }

    // 上传图片成功后 回调
    uploadafterfun = (picUrl) => {
        if (this.Loading) {
            this.Loading.hide();
        }
        let data = this.state.data
        if (imgType == 'storeImg') {
            data.storePic = picUrl
        } else if (imgType == 'logoImg') {
            data.merchantLogoPic = picUrl
        }
        this.setState({
            data: data
        })
    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    rightBox: {
        height: '100%',
        width: 70,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
    },
    rightText: {
        fontSize: 16,
        color: '#333333',
        fontWeight: 'bold',
    },
    dutyBox: {
        width: '100%',
        height: 100,
        flexDirection: 'column',
        justifyContent: 'flex-start'
    },
    storeInfoBox: {
        width: '100%',
        height: 230,

    },
    storeImg: {
        width: '100%',
        height: '100%',
    },
    storeBottomBox: {
        position: 'absolute',
        bottom: 0,
        width: '100%',
        height: 89,
        backgroundColor: 'rgba(255,255,255,0.8)',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 15,
    },
    storeLogoText: {
        color: '#333',
        fontSize: 16
    },
    logoImg: {
        width: 54,
        height: 54,
        borderRadius: 27
    },
    arrowImg: {
        marginLeft: 10,
        width: 15,
        height: 15
    },
    sectionBox: {
        flexDirection: 'column',
        paddingHorizontal: 15,
        backgroundColor: '#fff',
    },
    storeItemBox: {
        width: '100%',
        height: 44,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        borderBottomColor: '#e4e4e4',
        borderBottomWidth: 0.3
    },
    leftBox: {
        flexDirection: 'row',
        alignItems: 'center',
        width: 68
    },
    storeItemBox1: {
        width: '100%',
        height: 44,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    storeItemBox2: {
        minHeight: 44,
        width: '100%',
        paddingVertical: 10,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    storeTitleText: {
        color: '#333',
        fontSize: 14,
    },
    necessaryText: {
        marginLeft: 5,
        color: 'red',
        fontSize: 14,
    },
    textInput: {
        marginLeft: 25,
        flex: 1,
        height: '100%',
        color: '#333'
    },
    storeDesText: {
        textAlign: 'left',
        flex: 1,
        color: '#333',
        fontSize: 14,
        marginLeft: 25,
        lineHeight: 20,
    },
    introDes: {
        marginTop: 6,
        fontSize: 14,
        color: '#333',
        lineHeight: 20

    },
    locationImg: {
        marginLeft: 30,
        width: 66,
        height: 20
    },
    remarkBg: {
        marginTop: 10,
        width: '100%',
        height: 90,
        borderRadius: 4,
    },
    remarkTextInput: {
        flex: 1,
        height: '100%',
        textAlignVertical: 'top'
    },
    remarkCountText: {
        position: 'absolute',
        right: 12,
        bottom: 12,
        color: '#333',
        fontSize: 13
    },
    deleteBg: {
        marginTop: 15,
        width: '100%',
        paddingHorizontal: 15,
    },
    deleteBox: {
        marginTop: 5,
        width: '100%',
        height: 40,
        backgroundColor: '#FFE000',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 4
    },
    deleteText: {
        color: '#333',
        fontSize: 15
    }
})